package com.mxy.myapplication.util;

import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class MyItemDecoration extends RecyclerView.ItemDecoration {

    private Paint paint;
    //像素
    private int dividerHeight, dividerMarginLeft, dividerMarginRight;


    public MyItemDecoration(Resources resources, int colorID, int dividerHeight,
                            int dividerMarginLeft, int dividerMarginRight) {
        this.dividerHeight = dividerHeight;
        this.dividerMarginLeft = dividerMarginLeft;
        this.dividerMarginRight = dividerMarginRight;

        if (this.dividerHeight < 0) {
            this.dividerHeight = 0;
        }

        if (this.dividerMarginLeft < 0) {
            this.dividerMarginLeft = 0;
        }

        if (this.dividerMarginRight < 0) {
            this.dividerMarginRight = 0;
        }

        paint = new Paint();
        //设置抗锯齿
        paint.setAntiAlias(true);
        //设置抗像素抖动(俗称降噪)
        paint.setDither(true);
        paint.setColor(resources.getColor(colorID));
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        //不是第一个item
        if (parent.getChildAdapterPosition(view) != 0) {
            //像素
            outRect.top = dividerHeight;
        }
    }


    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        //获取屏幕上item的数量
        int itemCountOnScreen = parent.getChildCount();

        //遍历这些item
        for (int i = 0; i < itemCountOnScreen; i++) {
            //第一个item不需要绘制分割线
            if (parent.getChildAdapterPosition(parent.getChildAt(i)) != 0) {
                View view = parent.getChildAt(i);

                float dividerTop = view.getTop() - dividerHeight;
                float dividerLeft = view.getLeft() + this.dividerMarginLeft;
                float dividerBottom = view.getTop();
                float dividerRight = view.getRight() - this.dividerMarginRight;

                c.drawRect(dividerLeft, dividerTop, dividerRight, dividerBottom, this.paint);
            }
        }
    }

    @Override  //onDrawOver可以绘制一些图案，覆盖在itemView之上
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
    }
}